package com.firestone.core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

public class MD5Util {
	public static String encode32(String str) {
		if (str == null) {
			str = "";
		}

		byte[] sbyts = str.getBytes();
		return encode(sbyts);
	}

	public static String encode(byte[] sbyts) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] byts = md.digest(sbyts);

			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < byts.length; offset++) {
				int i = byts[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			return buf.toString();
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return "";
	}

	public static String encode(String str) {
		return encode32(str);
	}

	public static String encode16(String str) {
		String value = encode32(str);
		return value.substring(8, 24);
	}

	public static String md5(File f) {
		FileInputStream fis = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			fis = new FileInputStream(f);
			byte[] buffer = new byte[8192];
			int length;
			while ((length = fis.read(buffer)) != -1) {
				md.update(buffer, 0, length);
			}
			String str = new String(Hex.encodeHex(md.digest()));
			return str;
		} catch (FileNotFoundException e) {
			return null;
		} catch (Exception e) {
			return null;
		} finally {
			try {
				if (fis != null)
					fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static String md5(String target) {
		return DigestUtils.md5Hex(target);
	}

	public static String md5(byte[] byts) {
		return DigestUtils.md5Hex(byts);
	}

	public static void main(String[] args) {
        System.out.println(MD5Util.md5("北京诺华制药有限公司"));
    }
}